<template>
    <async-modal initHeight="600px" initWidth="800px" :title="`参数选择【${title}】`" @update:visible="cancel"
        @modalLoaded="init" :enable-loading="true">
        <template #modalBody>
            <el-form class="digBody" :model="formInfo" ref="ruleFormRef" label-width="120px" :rules="rules"
                style="width: 100%;">
                <el-form-item label="参数列表：" prop="params">
                    <el-table class="estimateParamTable" :data="formInfo.params">
                        <el-table-column prop="name" label="参数名称" min-width="110">
                            <template #default="scope">
                                <span class="text-danger" v-show="scope.row.isNotNull == 1">* </span>
                                {{ scope.row.name }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="dictOperator" label="操作符" min-width="110" align="center">
                            <template #default="scope">
                                {{ dictList.OPERATOR.map[scope.row.dictOperator] }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="value" label="参数值" min-width="210">
                            <template #default="scope">
                                <select-sim v-model="scope.row.columnPath" :property="'formColumnInfo'" :disabled="isRead"
                                    placeholder=""
                                    :formColumnInfoData="scope.row"
                                    :forReProcDefId="forReProcDefId" :defaultList="[{
                                        id: scope.row.columnPath,
                                        name: scope.row.columnName
                                    }]" :index="scope.$index" @save="saveSim01" style="width: 100%;" />
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
        </template>
        <template #modalFoot>
            <div class="event-button">
                <el-button type="primary" @click="onSubmit">确定</el-button>
                <el-button @click="cancel">取消</el-button>
            </div>
        </template>
    </async-modal>
</template>

<script setup lang="ts">
import AsyncModal from '@/components/Modal/index.vue';
import type { FormInstance } from 'element-plus';
import pubApi from '@/api/pub';
import selectSim from '@/components/remoteSelect/simple.vue';

import type { Dict } from '@/api/pub/type.ts';
const dictList = autoDict();

let $emit = defineEmits(['save', 'closeDig']);

interface InitProps {
    row: {
        riskBusinessName: string;
        params: any[];
    };
    index: number;
    
}

const props = defineProps({
    initMsg: {
        type: Object as PropType<InitProps>,
        default: () => ({})
    },
    isRead: {
        type: Boolean,
        default: false
    }
});


const rules = ref({
})
const forReProcDefId = inject('forReProcDefId', ref<number>(-1));
const riskCheckTypeList = ref<Dict[]>([]);
interface TreeNode {
    id: number;
    parentId: number;
    name: string;
    children?: TreeNode[];
}
const deptTreeList = ref<TreeNode[]>([]);
const getDeptList = async () => {
    try {
        let results = await pubApi.getDeptList({
            "dictDeptType": null,
            "dictDeptStatus": '1',
        }) as any;
        if (results) {
            // 接口调用成功
            deptTreeList.value = results;
        } else {
            // 处理接口调用成功，但返回结果为空的情况
            throw new Error("接口调用成功，但返回结果为空");
        }
    } catch (error) {
        // 处理接口调用失败的情况
        throw new Error("接口调用失败"); // 返回一个默认值或者进行其他错误处理
    }
};
const title = ref('');
const init = () => {
    riskCheckTypeList.value = dictList.RISK_CHECK_TYPE.list;
    getDeptList();
    
    title.value = props.initMsg.row.riskBusinessName;
    let params = JSON.parse(JSON.stringify(props.initMsg.row.params))
    // console.log('表格数据:',params);
    formInfo.params = params && params.length > 0 ? params : [];
    formInfo.params.forEach(item => {
        item.dictOperator = 3;
    });
};
interface FormInfo {
    id: number | null;
    params: any[];
}
const initialFormInfo: FormInfo = {
    id: null,
    params: [],
};

const formInfo = reactive({ ...initialFormInfo });
const cancel = () => {
    $emit('closeDig');
}
const ruleFormRef = ref<FormInstance>();
const onSubmit = async () => {
    if (formInfo.params.length > 0) {
        for (let i = 0; i < formInfo.params.length; i++) {
            const item = formInfo.params[i];
            // 确保 item.code 是字符串类型
            if (item.isNotNull === 1 && !item.columnPath) {
                ElMessage.error(`请填写 ${item.name}`);
                return;
            }
        }
    }
    let msg = {
        'params': formInfo.params,
        'index': props.initMsg.index,
    }
    $emit('save', msg);
    $emit('closeDig');
}
const saveSim01 = (msg: any) => {
    // console.log('选中2：', msg.item);
    formInfo.params[msg.index].columnPath = msg.item ? msg.item.columnPath : '';
    formInfo.params[msg.index].columnName = msg.item ? msg.item.columnName : '';
    formInfo.params[msg.index].columnCode = msg.item ? msg.item.columnCode : '';
}
</script>

<style scoped lang="scss">
.partTitle {
    padding-left: 12px;
}

.detailsContent {
    padding: 0 30px 15px;
}

:deep(.estimateParamTable.el-table) .el-table__cell {
    padding: 4px 0;
}

.digBody {
    height: calc(100% - 10px);

    .subBtn {
        position: absolute;
        right: 30px;
        top: 0;
    }
}
</style>
